package com.smartwebx.ha.dal.util;

import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.smartwebx.ha.dal.usebean.DateValue;
import com.smartwebx.ha.dal.usebean.DateValueTotal;
import com.smartwebx.ha.dal.usebean.abstr.AbstractIntId;
import com.smartwebx.ha.dal.usebean.abstr.AbstractStrId;
import com.smartwebx.ha.dal.usebean.abstr.AbstractStation;
import com.smartwebx.ha.dal.usebean.abstr.AbstractValue;

public class MyFunctions {

	public static Function<AbstractStation, String> getStationFuns() {
		return new Function<AbstractStation, String>() {
			@Override
			public String apply(AbstractStation input) {
				return Objects.firstNonNull(input.getStcd(), "");
			}
		};
	}

	public static Function<AbstractValue, Double> getValueFuns() {
		return new Function<AbstractValue, Double>() {
			@Override
			public Double apply(AbstractValue input) {
				return Objects.firstNonNull(input.getVal(), 0d);
			}
		};
	}

	public static Function<DateValue, DateValueTotal> transformDateValueTotal() {
		return new Function<DateValue, DateValueTotal>() {
			Double sum = 0d;

			@Override
			public DateValueTotal apply(DateValue dv) {
				DateValueTotal dateValueT = new DateValueTotal(dv);
				sum += dv.getVal();
				dateValueT.setTotalVal(sum);
				return dateValueT;
			}
		};
	}

	public static <T extends Number> Function<String, T> parseNumberFunctionFor(
			final Class<T> type) {

		return new Function<String, T>() {
			@SuppressWarnings("unchecked")
			public T apply(String input) {
				T result = null;
				if (type == Integer.class) {
					result = (T) Ints.tryParse(input);
				} else if (type == Long.class) {
					result = (T) Longs.tryParse(input);
				}else if(type == Double.class){
					result = (T)Doubles.tryParse(input);
				}
				return result;
			}
		};
	}

	public static Function<AbstractStrId, String> getStrIdFuns() {
		return new Function<AbstractStrId, String>() {
			public String apply(AbstractStrId input) {
				return input.getId();
			}
		};
	}

	public static Function<AbstractIntId, Integer> getIntIdFuns() {
		return new Function<AbstractIntId, Integer>() {
			public Integer apply(AbstractIntId input) {
				return input.getId();
			}
		};
	}

}
